<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <!-- 条件栏 -->
    <page-filter
      v-model:query="filterInfo.query"
      :filter-list="filterInfo.list"
    >
      <template v-slot:filter-contractNameLike>
        <div class="scan-groups">
          <el-input
            v-model="filterInfo.query.contractNameLike"
            :clearable="true"
            placeholder="请输入名称"
            @keyup.enter.native="search"
            @input="(e) => (filterInfo.contractNameLike = validSe(e))"
          >
          </el-input>
        </div> </template
    ></page-filter>
    <dialog-table
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :listen-height="false"
      :tab-index="tabIndex"
      :query="filterInfo.query"
      :field-list="
        changeContract ? tableInfo.changeFieldList : tableInfo.fieldList
      "
      :selectable="selectable"
      :handle="tableInfo.handle"
      :highlight-row="highlightRow"
      :check-box="!changeContract && checkBox"
      :checkedList="checkBox ? checkedList : []"
      :pager="changeContract ? false : true"
      @handleEvent="handleEvent"
    />
  </page-dialog>
</template>

<script setup name="selectContractNoCustomize">
import { getContractList, getProductByContract } from '@/api/contract'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: true,
  },
  checkBox: {
    type: Boolean,
    default: false,
  },
  selectable: {
    type: Function,
  },
  tabIndex: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getContractList,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  checkedList: {
    type: Array,
    default: function () {
      return []
    },
  },
  saveEmpty: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: function () {
      return []
    },
  },
  changeContract: {
    type: Boolean,
    default: false,
  },
})

// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: '',
    contractNameLike: '',
    isEnable: 1,
    contractType: 2,
    status: 4,
    ...props.query,
  },
  list: [
    {
      type: 'slot',
      label: '名称',
      value: 'contractNameLike',
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  copyData: [],
  selections: [],
  fieldList: [
    { label: '合同编号', value: 'orderNo' },
    { label: '合同名称', value: 'contractName' },
    { label: '合同类型', value: 'contractTypeValue' },
    { label: '供应商', value: 'supplierName' },
    { label: '签订部门', value: 'signDeptName' },
    { label: '签订日期', value: 'signDate' },
  ],
  changeFieldList: [
    { label: '合同编号', value: 'orderNo' },
    { label: '合同名称', value: 'contractName' },
    { label: '供应商', value: 'supplierName' },
    { label: '供应商价格', value: 'price' },
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: '选择合同',
  btLoading: false,
  width: '600px',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: !props.saveEmpty,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref('')

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    if ((props.data && props.data.length) || props.changeContract) {
      //父组件传的列表数据
      tableInfo.value.data = props.data
      tableInfo.value.copyData = proxy.$fn.deepClone(props.data)
    } else {
      getList()
    }
  })
})

// 获取列表
function getList() {
  tableInfo.value.api = props.api
  tableInfo.value.refresh = Math.random()
}
function search() {
  if (props.data && props.data.length) {
    const search = filterInfo.value.query.contractNameLike
    if (search) {
      tableInfo.value.data = tableInfo.value.copyData.filter((data) => {
        return Object.keys(data).some((key) => {
          if (key === 'orderNo') {
            return String(data[key]).indexOf(search) > -1
          } else if (key === 'contractName') {
            return String(data[key]).indexOf(search) > -1
          }
        })
      })
    } else {
      tableInfo.value.data = tableInfo.value.copyData
    }
  } else {
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
}
function save() {
  if (props.changeContract) {
    handleClose()
    emits('callback', selectRow.value)
    return
  }
  const ids = selectRow.value
    .map((item) => {
      return item.id
    })
    .toString()
  getProductByContract({ contractIds: ids }).then((res) => {
    if (res.success) {
      if (res.msg) {
        proxy.$message({
          showClose: true,
          message: res.msg,
          type: 'warning',
          duration: 3500,
        })
      }
      handleClose()
      emits('callback', res.data)
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      selectRow.value = data
      if (!props.saveEmpty) {
        dialogInfo.value.btList[1].disabled = !(
          selectRow.value &&
          (selectRow.value.length || selectRow.value.id)
        )
      }
      break
    case 'tableCheck':
      selectRow.value = data
      if (!props.saveEmpty) {
        dialogInfo.value.btList[1].disabled = !(
          selectRow.value &&
          (selectRow.value.length || selectRow.value.id)
        )
      }
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
</script>

<style scoped></style>
